package code.lucamarrocco.rest;

import static code.lucamarrocco.rest.Cases.*;

import java.util.*;

public class Signatures {
	private static final String crud(String verb) {
		if (verb.equalsIgnoreCase("POST")) return "create";
		if (verb.equalsIgnoreCase("GET")) return "read";
		if (verb.equalsIgnoreCase("PUT")) return "update";
		if (verb.equalsIgnoreCase("DELETE")) return "delete";
		return verb;
	}

	private static final List<String> signatureOf(Collection<String> parameterNames) {
		List<String> signatures = new LinkedList<String>();
		for (String parameter : parameterNames) {
			boolean isId = parameter.toLowerCase().endsWith("id");
			if (isId) signatures.add(new Formatter().format("Long %s", parameter).toString());
			if (!isId) signatures.add(new Formatter().format("String %s", parameter).toString());
		}
		return signatures;
	}

	public static final String topicSignatureOf(RestfulMethod method) {
		StringBuilder signatureBuilder = new StringBuilder();
		signatureBuilder.append(method.getTopic());
		signatureBuilder.append(signatureOf(method));
		return signatureBuilder.toString();
	}

	public static final String signatureOf(RestfulMethod method) {
		List<String> parameters = signatureOf(method.getNames());

		StringBuilder signatureBuilder = new StringBuilder();
		signatureBuilder.append(simpleSignatureOf(method));
		signatureBuilder.append("(");
		for (String parameter : parameters) {
			signatureBuilder.append(parameter).append(", ");
		}
		signatureBuilder.append(")");

		return signatureBuilder.toString().replaceAll(", \\)$", ")");
	}

	public static final String simpleSignatureOf(RestfulMethod method) {
		String verb = crud(method.getVerb().toLowerCase());
		String resource = method.getResource().toLowerCase();
		String anotherVerb = method.getAnotherVerb().toLowerCase();

		return asCamelCase(verb, resource, anotherVerb);
	}
}